// EDataTable.qml
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Effects
import "qrc:/component/ZGlobal.js" as Global

Item {
    id: rootLogPage
    clip: false

    // === 接口属性 & 信号 ===
    property var headers:  [
        { key: "id", label: "ID", w: 60},
        { key: "name", label: "用户", w: 150 },
        { key: "real_name", label: "姓名", w: 150 },
        { key: "create_time", label: "日期时间", w: 250 },
        { key: "type", label: "运行项目", w: 200 },
        // { key: "key_info", label: "运行结果", w:130 },
        { key: "desc", label: "执行内容", w:0 },
    ]
    property var model: operationInfo
    property bool selectable: false
    signal rowClicked(int index, var rowData)
    signal checkStateChanged(int index, var rowData, bool isChecked)
    signal editClicked(int index, var rowData)
    signal addClicked()

    // === 样式属性 ===
    property bool backgroundVisible: true
    property real radius: 12
    property int headerHeight: 60
    property int rowHeight: 54
    property int fontSize: 24
    property int cellPadding:62
    property real pressedScale: 0.97
    property color headerColor: theme.secondaryColor
    property color rowColor: "#FFFFFF"
    property color hoverColor: Qt.darker(rowColor, 1.0)
    property color textColor: "#333"
    property color headerTextColor: theme.textColor
    property bool shadowEnabled: true
    property color shadowColor: theme.shadowColor
    property color checkmarkColor: theme.focusColor
    property int boxSize:10

    property color gridLineColor: "#DDE7F5"

    // === 动态列宽数组 ===
    property var columnWidths: []
    // 外部可注入的头部工具区内容
    //property alias headerTools: headerToolsContainer.data

    TextMetrics {
        id: textMetrics
        font.pixelSize: rootLogPage.fontSize
    }

    // === 响应式表头全选状态 ===
    property string headerCheckState: "none" // none / all / partial

    onRowClicked: function(index, rowData) {
        console.log("点击行：", index, rowData.name)
    }

    onEditClicked: function(index, rowData) {
        console.log("编辑行：", index, rowData.id, ">>", swipeView.contentChildren[1].name)
        var user = userInfo.get(index);
        console.log("name:", user.name, " real_name", userPage.name," id:", user.id)
        userPage.fillData(index, user)
        swipeView.currentIndex = 1;
    }
    onAddClicked: function() {
        console.log("添加用户>>>>>")
        swipeView.currentIndex = 1
    }

    onVisibleChanged: {
        if(visible){
            operationInfo.loadOperation("");
        }
    }

    // 计算内容总宽度（考虑特殊列的最小宽度）
    function effectiveColumnWidth(index) {
        return headers[index].w;
    }

    function computeContentWidth() {
        var sum = rootLogPage.selectable ? 40 : 0;
        if (!headers || headers.length === 0) return sum;
        for (var i = 0; i < headers.length; i++) {
            sum += effectiveColumnWidth(i);
        }
        return sum;
    }

    // === 背景与阴影===
    Rectangle {
        id: background
        width: parent.width
        anchors.fill: parent
        border.width: 1
        border.color: "#D1D3D8"
        radius: rootLogPage.radius
        color: rootLogPage.backgroundVisible ? rootLogPage.rowColor : "transparent"


        // 顶部工具栏容器（用于放置标题按钮等）
        Item{
            id: toolBar
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.top: parent.top
            height:88
            anchors.leftMargin: 40
            anchors.rightMargin: 40
            Rectangle {
                id: titleAccent
                anchors.verticalCenter: parent.verticalCenter
                width: 16
                height: 31
                color: theme.focusColor
            }
            Text {
                anchors.left: titleAccent.right
                anchors.leftMargin: 12
                anchors.verticalCenter: parent.verticalCenter
                text: "设备日志"
                font.bold: true
                font.pixelSize: 32
                color: "#333"
                verticalAlignment: Text.AlignVCenter
            }

            // 右侧：查询与操作
            Row {
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                spacing: 15

                EInput {
                    width: 570
                    backgroundColor: "#EAEDF4"
                    radius: 12
                    placeholderText: "请输入查询内容"
                    iconCharacter: "\uf002"
                    iconColor: "#9AA5B1"
                    onTextChanged:{
                        console.log("text:",text)
                        userInfo.loadUser(text);
                    }
                }

                // 打印
                Item {
                    id: printBtn
                    width: 60
                    height: 60
                    property bool pressed: false
                    scale: pressed ? 0.95 : 1
                    Image {
                        anchors.fill: parent
                        source: "qrc:/assets/print.png"
                        fillMode: Image.PreserveAspectFit
                        smooth: true
                        mipmap: true
                    }
                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onPressed: printBtn.pressed = true
                        onReleased: printBtn.pressed = false
                        onClicked: console.log("打印")
                    }
                }

                // 添加用户
                Item {
                    id: addBtn
                    width: 60
                    height: 60
                    property bool pressed: false
                    scale: pressed ? 0.95 : 1
                    Image {
                        anchors.fill: parent
                        source: "qrc:/assets/adduser.png"
                        fillMode: Image.PreserveAspectFit
                        smooth: true
                        mipmap: true
                    }
                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        onPressed: addBtn.pressed = true
                        onReleased: addBtn.pressed = false
                        onClicked: {
                            rootLogPage.addClicked()
                            console.log("添加用户")
                        }
                    }
                }
            }
        }

        Column {
            anchors.top: toolBar.bottom
            width: parent.width
            height: parent.height
            // === 表头 ===
            Row {
                id: headerRow
                height: rootLogPage.headerHeight
                width: parent.width
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 0

                // 数据列头
                Repeater {
                    model: rootLogPage.headers
                    delegate: Rectangle {
                        width: effectiveColumnWidth(index) ===0 ? headerRow.width-computeContentWidth():effectiveColumnWidth(index)
                        height: parent.height
                        color: rootLogPage.backgroundVisible ? "#208FCD" : "transparent"
                        border.width: 1
                        border.color: gridLineColor

                        Text {
                            anchors.centerIn: parent
                            text: modelData.label
                            font.pixelSize: rootLogPage.fontSize
                            font.bold: true
                            color: rootLogPage.headerTextColor
                            elide: Text.ElideRight
                        }
                    }
                }
            }

            // === 数据区 ===
            ListView {
                id: tableView
                width: parent.width
                height: background.height - headerRow.height-100
                spacing: 0
                anchors.horizontalCenter: parent.horizontalCenter
                model: rootLogPage.model
                clip: true

                delegate: Rectangle {
                    id: rowContainer
                    width: headerRow.width
                    height: rootLogPage.rowHeight
                    radius: rootLogPage.radius * 0.5
                    property bool checked: (model.checked !== undefined) ? model.checked : false
                    property var rowData: model
                    property int rowIndex: index
                    property bool hovered: false

                    color: "transparent"
                    opacity: 1.0

                    Behavior on color { ColorAnimation { duration: 150 } }
                    Behavior on opacity { NumberAnimation { duration: 100 } }

                    transform: Scale {
                        id: scale
                        origin.x: rowContainer.width / 2
                        origin.y: rowContainer.height / 2
                    }

                    ParallelAnimation {
                        id: restoreAnimation
                        SpringAnimation { target: scale; property: "xScale"; to: 1.0; spring: 2.5; damping: 0.25 }
                        SpringAnimation { target: scale; property: "yScale"; to: 1.0; spring: 2.5; damping: 0.25 }
                    }

                    Row {
                        anchors.fill: parent
                        anchors.horizontalCenter: parent.horizontalCenter
                        spacing: 0

                        // 数据列
                        Repeater {
                            model: rootLogPage.headers
                            delegate: Rectangle {
                                property bool isActionCol: modelData.key === "actions"
                                property bool isStatusCol: modelData.key === "status"
                                property bool isPermissionCol: modelData.key === "permission"
                                width: effectiveColumnWidth(index) ===0 ? headerRow.width-computeContentWidth():effectiveColumnWidth(index)
                                height: parent.height
                                color: "transparent"
                                border.width: 1
                                border.color: gridLineColor

                                // 普通数据列
                                Text {
                                    visible: !isActionCol && !isStatusCol && !isPermissionCol
                                    anchors.centerIn: parent
                                    text: displayValue(modelData.key, rowData)
                                    color: rootLogPage.textColor
                                    font.pixelSize: rootLogPage.fontSize
                                    elide: Text.ElideRight
                                }

                                // 权限列：数字不显示，改为中文标签
                                Text {
                                    visible: isPermissionCol
                                    anchors.centerIn: parent
                                    text: Global.permissionLabel(rowContainer.rowData.permission)
                                    color: rootLogPage.textColor
                                    font.pixelSize: rootLogPage.fontSize
                                    elide: Text.ElideRight
                                }

                                // 状态列：1 显示绿色勾，0 显示红色 x
                                Text {
                                    visible: isStatusCol
                                    anchors.centerIn: parent
                                    text: ((rowContainer.rowData.status === "1") || (rowContainer.rowData.status === 1)) ? "\u2713 " + "许可" : "\u2715 " + "禁止"
                                    color: ((rowContainer.rowData.status === "1") || (rowContainer.rowData.status === 1)) ? "#43A047" : "#E53935"
                                    font.pixelSize: rootLogPage.fontSize
                                }

                                // 操作列：编辑
                                Text {
                                    id: editText
                                    visible: isActionCol
                                    anchors.centerIn: parent
                                    text: "修改"
                                    color: "#2090CD"
                                    font.pixelSize: rootLogPage.fontSize
                                }
                                MouseArea {
                                    visible: isActionCol
                                    anchors.fill: parent
                                    cursorShape: Qt.PointingHandCursor
                                    onClicked: rootLogPage.editClicked(rowContainer.rowIndex, rowContainer.rowData)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // 显示值格式化（时间列显示完整时间）
    function displayValue(key, rowObj) {
        var v = rowObj[key];
        if (v === undefined) return "-";
        var s = String(v);
        // 时间列显示完整时间格式，不再截取
        return s;
    }
}
